package top.snoweagle.simple.console.security.filter;

import top.snoweagle.simple.console.security.enums.AuthEnum;
import top.snoweagle.simple.console.security.enums.PropertiesEnum;
import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.http.HttpStatus;
import org.springframework.web.filter.OncePerRequestFilter;

import javax.servlet.*;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.util.ResourceBundle;

public class SecurityFilter extends OncePerRequestFilter {
    protected final Logger logger = LoggerFactory.getLogger(this.getClass());


    @Override
    protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain)
            throws ServletException, IOException {

        // 获取url
        String url = request.getRequestURI();
        String context = request.getContextPath();
        logger.debug("[ 请求 ] URL：{}",url);

        // 是否session检查
        boolean doCheck = true;
        if(url.equals(context)||url.equals(context + "/")) {
            //首页不需要check
            doCheck = false;
        }else{
            //获取安全配置
            ResourceBundle rb = (ResourceBundle)getServletContext().getAttribute("SECURITY_CONFIG");
            String notAccessStr = rb.getString(PropertiesEnum.NOT_ACCESSS_PATH.getKey());
            String[] notAccessArr = StringUtils.split(notAccessStr,",");

            for (String s : notAccessArr) {
                if (StringUtils.isEmpty(s)) {
                    continue;
                }
                if (StringUtils.contains(url, s)) {
                    //需鉴权
                    doCheck = false;
                    break;
                }
            }
        }

        if(doCheck){
            HttpSession session =request.getSession();
            logger.info("[ seesion检查 ] url：{} session:{}", url ,session.getId());
//            User user = (User)session.getAttribute("CURRENT_USER");
// if(user==null){
            String token = (String)session.getAttribute(AuthEnum.Token.getCode());
            if(StringUtils.isEmpty(token)){
                logger.warn("[ 用户session超时! ]");
                boolean isAjaxRequest = isAjaxRequest(request);
                if (isAjaxRequest)
                {
                    response.sendError(HttpStatus.UNAUTHORIZED.value(), "您已经太长时间没有操作,请刷新页面");
                    return ;
                }else{
                    response.sendRedirect(context);
                }
            }else{
                logger.warn("[ session有效! ]");
                filterChain.doFilter(request, response);
            }
        }else {
            filterChain.doFilter(request, response);
        }
    }

    public static boolean isAjaxRequest(HttpServletRequest request)
    {
        String header = request.getHeader("X-Requested-With");
        if (header != null && "XMLHttpRequest".equals(header))
            return true;
        else
            return false;
    }


}
